<template>
  <div class="ssh-manager">
    <!-- 左侧主机列表 -->
    <div class="hosts-sidebar" :class="{ 'collapsed': sidebarCollapsed }">
      <div class="sidebar-header">
        <div class="header-title">
          <span class="title-icon">🖥️</span>
          <span v-if="!sidebarCollapsed" class="title-text">主机列表</span>
        </div>
        <button @click="sidebarCollapsed = !sidebarCollapsed" class="collapse-btn" :title="sidebarCollapsed ? '展开' : '收起'">
          <span v-if="sidebarCollapsed">→</span>
          <span v-else>←</span>
        </button>
      </div>

      <div v-if="!sidebarCollapsed" class="sidebar-body">
        <!-- 搜索框 -->
        <div class="search-box">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="🔍 搜索主机..."
            class="search-input"
          />
        </div>

        <!-- 快速连接所有在线主机 -->
        <div class="quick-actions">
          <button @click="connectAllOnline" class="btn-quick" title="连接所有在线主机">
            <span>⚡</span>
            <span>全部连接</span>
          </button>
          <button @click="refreshHosts" class="btn-quick" title="刷新主机列表">
            <span :class="{ 'spinning': isRefreshing }">🔄</span>
            <span>刷新</span>
          </button>
        </div>

        <!-- 主机组列表 -->
        <div class="groups-list">
          <div v-if="loading" class="loading-state">
            <div class="spinner"></div>
            <span>加载中...</span>
          </div>

          <div v-else>
            <!-- 未分组主机 -->
            <div v-if="ungroupedHosts.length > 0" class="group-item">
              <div class="group-header" @click="toggleGroup(null)">
                <span class="toggle-icon">{{ expandedGroups[null] ? '▼' : '▶' }}</span>
                <span class="group-name">未分组主机</span>
                <span class="group-count">{{ ungroupedHosts.length }}</span>
              </div>
              <div v-show="expandedGroups[null]" class="hosts-list">
                <div 
                  v-for="host in ungroupedHosts" 
                  :key="host.id"
                  class="host-item"
                  :class="{ 
                    'active': activeTerminals.some(t => t.hostId === host.id),
                    'offline': host.status !== 'online' 
                  }"
                  @click="connectToHost(host)"
                  :title="`${host.name} (${host.ip}:${host.port})`"
                >
                  <span class="host-status" :class="'status-' + host.status">●</span>
                  <span class="host-name">{{ host.name }}</span>
                  <span class="host-ip">{{ host.ip }}</span>
                  <span v-if="activeTerminals.some(t => t.hostId === host.id)" class="connected-badge">已连接</span>
                </div>
              </div>
            </div>

            <!-- 按组分类的主机 -->
            <div v-for="group in filteredGroups" :key="group.id" class="group-item">
              <div class="group-header" @click="toggleGroup(group.id)">
                <span class="toggle-icon">{{ expandedGroups[group.id] ? '▼' : '▶' }}</span>
                <span class="group-icon">📁</span>
                <span class="group-name">{{ group.name }}</span>
                <span class="group-count">{{ getGroupHosts(group.id).length }}</span>
              </div>
              <div v-show="expandedGroups[group.id]" class="hosts-list">
                <div 
                  v-for="host in getGroupHosts(group.id)" 
                  :key="host.id"
                  class="host-item"
                  :class="{ 
                    'active': activeTerminals.some(t => t.hostId === host.id),
                    'offline': host.status !== 'online' 
                  }"
                  @click="connectToHost(host)"
                  :title="`${host.name} (${host.ip}:${host.port})`"
                >
                  <span class="host-status" :class="'status-' + host.status">●</span>
                  <span class="host-name">{{ host.name }}</span>
                  <span class="host-ip">{{ host.ip }}</span>
                  <span v-if="activeTerminals.some(t => t.hostId === host.id)" class="connected-badge">已连接</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧终端区域 -->
    <div class="terminals-area">
      <!-- 终端Tabs -->
      <div v-if="activeTerminals.length > 0" class="terminals-tabs">
        <div class="tabs-list">
          <div 
            v-for="(terminal, index) in activeTerminals" 
            :key="terminal.id"
            class="tab-item"
            :class="{ 'active': currentTerminalIndex === index }"
            @click="switchTerminal(index)"
          >
            <span class="tab-icon">⚡</span>
            <span class="tab-name">{{ terminal.hostName }}</span>
            <span class="tab-ip">{{ terminal.hostIp }}</span>
            <button @click.stop="closeTerminal(terminal.id)" class="tab-close">✕</button>
          </div>
        </div>
        <div class="tabs-actions">
          <button @click="closeAllTerminals" class="btn-close-all" title="关闭所有终端">
            <span>✕</span>
            <span>关闭全部</span>
          </button>
        </div>
      </div>

      <!-- 终端内容 -->
      <div class="terminals-content">
        <div v-if="activeTerminals.length === 0" class="empty-state">
          <div class="empty-icon">🖥️</div>
          <h3>暂无活动连接</h3>
          <p>从左侧主机列表选择一台主机开始连接</p>
          <div class="empty-tips">
            <div class="tip-item">
              <span class="tip-icon">💡</span>
              <span>提示：点击主机名即可建立SSH连接</span>
            </div>
            <div class="tip-item">
              <span class="tip-icon">⚡</span>
              <span>支持同时连接多台主机</span>
            </div>
            <div class="tip-item">
              <span class="tip-icon">🎯</span>
              <span>按F11进入全屏模式</span>
            </div>
          </div>
        </div>

        <div 
          v-for="(terminal, index) in activeTerminals" 
          :key="terminal.id"
          v-show="currentTerminalIndex === index"
          class="terminal-panel"
        >
          <Terminal 
            :host-id="terminal.hostId" 
            :host-name="terminal.hostName"
            @close="closeTerminal(terminal.id)"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import api from '@/services/api'
import Terminal from '@/components/Terminal.vue'
import permissionAlert from '@/utils/permissionAlert'
import confirmDialog from '@/utils/confirmDialog'

// 数据状态
const hosts = ref([])
const groups = ref([])
const activeTerminals = ref([])
const currentTerminalIndex = ref(0)
const expandedGroups = ref({})
const sidebarCollapsed = ref(false)
const searchQuery = ref('')
const loading = ref(false)
const isRefreshing = ref(false)

// 计算属性
const ungroupedHosts = computed(() => {
  const filtered = hosts.value.filter(host => !host.host_group)
  return filterHosts(filtered)
})

const filteredGroups = computed(() => {
  if (!searchQuery.value) {
    return groups.value
  }
  return groups.value.filter(group => {
    const groupHosts = getGroupHosts(group.id)
    return groupHosts.length > 0 || group.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  })
})

// 过滤主机
const filterHosts = (hostList) => {
  if (!searchQuery.value) return hostList
  const query = searchQuery.value.toLowerCase()
  return hostList.filter(host => 
    host.name.toLowerCase().includes(query) || 
    host.ip.toLowerCase().includes(query)
  )
}

// 获取组内主机
const getGroupHosts = (groupId) => {
  const filtered = hosts.value.filter(host => host.host_group === groupId)
  return filterHosts(filtered)
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const [hostsData, groupsData] = await Promise.all([
      api.getHosts(),
      api.getHostGroups()
    ])
    
    hosts.value = Array.isArray(hostsData) ? hostsData : (hostsData.results || [])
    groups.value = Array.isArray(groupsData) ? groupsData : (groupsData.results || [])
    
    // 默认展开所有组
    groups.value.forEach(group => {
      expandedGroups.value[group.id] = true
    })
    expandedGroups.value[null] = true // 展开未分组
  } catch (error) {
    console.error('加载数据失败:', error)
    const errorMsg = error.response?.data?.error || error.response?.data?.detail || error.message
    permissionAlert.show({
      title: '加载失败 (｡•́︿•̀｡)',
      message: `加载主机列表失败～\n${errorMsg}`
    })
  } finally {
    loading.value = false
  }
}

// 刷新主机列表
const refreshHosts = async () => {
  isRefreshing.value = true
  await loadData()
  setTimeout(() => {
    isRefreshing.value = false
  }, 500)
}

// 切换组展开/收起
const toggleGroup = (groupId) => {
  expandedGroups.value[groupId] = !expandedGroups.value[groupId]
}

// 连接到主机
const connectToHost = async (host) => {
  if (host.status !== 'online') {
    const confirmed = await confirmDialog.show({
      title: '主机离线',
      message: `主机 ${host.name} 当前状态为离线\n是否仍要尝试连接？`
    })
    if (!confirmed) {
      return
    }
  }

  // 检查是否已经连接
  const existingIndex = activeTerminals.value.findIndex(t => t.hostId === host.id)
  if (existingIndex !== -1) {
    // 已连接，切换到该终端
    currentTerminalIndex.value = existingIndex
    return
  }

  // 创建新终端
  const terminalId = Date.now()
  activeTerminals.value.push({
    id: terminalId,
    hostId: host.id,
    hostName: host.name,
    hostIp: host.ip
  })
  currentTerminalIndex.value = activeTerminals.value.length - 1
}

// 连接所有在线主机
const connectAllOnline = async () => {
  const onlineHosts = hosts.value.filter(h => h.status === 'online')
  if (onlineHosts.length === 0) {
    permissionAlert.show({
      title: '提示 (｡•́︿•̀｡)',
      message: '没有在线的主机哦～\n请先确保有主机在线状态'
    })
    return
  }

  if (onlineHosts.length > 10) {
    const confirmed = await confirmDialog.show({
      title: '批量连接确认',
      message: `将连接 ${onlineHosts.length} 台主机\n这可能会占用较多资源\n是否继续？`
    })
    if (!confirmed) {
      return
    }
  }

  onlineHosts.forEach(host => {
    // 避免重复连接
    if (!activeTerminals.value.some(t => t.hostId === host.id)) {
      connectToHost(host)
    }
  })
}

// 切换终端
const switchTerminal = (index) => {
  currentTerminalIndex.value = index
}

// 关闭终端
const closeTerminal = (terminalId) => {
  const index = activeTerminals.value.findIndex(t => t.id === terminalId)
  if (index !== -1) {
    activeTerminals.value.splice(index, 1)
    
    // 调整当前终端索引
    if (currentTerminalIndex.value >= activeTerminals.value.length) {
      currentTerminalIndex.value = Math.max(0, activeTerminals.value.length - 1)
    }
  }
}

// 关闭所有终端
const closeAllTerminals = () => {
  if (confirm(`确定要关闭所有 ${activeTerminals.value.length} 个终端连接吗？`)) {
    activeTerminals.value = []
    currentTerminalIndex.value = 0
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.ssh-manager {
  display: flex;
  height: calc(100vh - 60px);
  background: var(--color-bg-primary);
  overflow: hidden;
}

/* 左侧主机列表 */
.hosts-sidebar {
  width: 320px;
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.98) 0%, rgba(250, 250, 252, 0.98) 100%);
  border-right: 2px solid rgba(255, 182, 193, 0.2);
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  position: relative;
  z-index: 10;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
}

.hosts-sidebar.collapsed {
  width: 60px;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, rgba(255, 182, 193, 0.08), rgba(255, 255, 255, 0.5));
  border-bottom: 1px solid rgba(255, 182, 193, 0.15);
}

.header-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title-icon {
  font-size: 20px;
  filter: drop-shadow(0 2px 4px rgba(255, 182, 193, 0.3));
}

.title-text {
  color: #FF1493;
  font-size: 16px;
  font-weight: 700;
}

.collapse-btn {
  padding: 6px 10px;
  background: #fff;
  border: 1.5px solid rgba(255, 182, 193, 0.3);
  border-radius: 6px;
  color: #FF1493;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(255, 20, 147, 0.1);
}

.collapse-btn:hover {
  background: linear-gradient(135deg, #FF1493, #FF69B4);
  border-color: #FF1493;
  color: #fff;
  transform: scale(1.05);
}

.sidebar-body {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 16px;
}

/* 搜索框 */
.search-box {
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
  padding: 10px 14px;
  background: #fff;
  border: 1.5px solid rgba(255, 182, 193, 0.2);
  border-radius: 8px;
  color: #333;
  font-size: 13px;
  transition: all 0.3s ease;
}

.search-input:focus {
  outline: none;
  border-color: #FF1493;
  background: #fff;
  box-shadow: 0 0 0 3px rgba(255, 20, 147, 0.1);
}

.search-input::placeholder {
  color: rgba(0, 0, 0, 0.4);
}

/* 快速操作 */
.quick-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.btn-quick {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 12px;
  background: #fff;
  border: 1.5px solid rgba(255, 182, 193, 0.25);
  border-radius: 8px;
  color: #FF1493;
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.btn-quick:first-child {
  background: linear-gradient(135deg, #FF1493, #FF69B4);
  border-color: #FF1493;
  color: #fff;
}

.btn-quick:first-child:hover {
  background: linear-gradient(135deg, #DC143C, #FF1493);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 20, 147, 0.3);
}

.btn-quick:last-child {
  background: linear-gradient(135deg, #1E90FF, #00BFFF);
  border-color: #1E90FF;
  color: #fff;
}

.btn-quick:last-child:hover {
  background: linear-gradient(135deg, #0066CC, #1E90FF);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(30, 144, 255, 0.3);
}

.spinning {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 主机组和列表 */
.groups-list { display: flex; flex-direction: column; gap: 0; }
.loading-state { display: flex; flex-direction: column; align-items: center; padding: 40px 20px; color: #666; gap: 12px; }
.spinner { width: 30px; height: 30px; border: 3px solid rgba(255,182,193,0.2); border-top-color: #FFB6C1; border-radius: 50%; animation: spin 1s linear infinite; }
.group-item { background: #fff; border: 1.5px solid rgba(255,182,193,0.15); border-radius: 8px; overflow: hidden; transition: all 0.3s; box-shadow: 0 2px 4px rgba(0,0,0,0.03); margin-bottom: 8px; }
.group-item:hover { border-color: rgba(255,20,147,0.3); box-shadow: 0 3px 10px rgba(255,20,147,0.1); }
.group-header { display: flex; align-items: center; gap: 8px; padding: 12px 14px; cursor: pointer; background: rgba(255,182,193,0.03); transition: all 0.2s; }
.group-header:hover { background: rgba(255,182,193,0.08); }
.toggle-icon { color: #FF1493; font-size: 12px; transition: transform 0.3s; }
.group-icon { font-size: 16px; }
.group-name { flex: 1; color: #FF1493; font-size: 14px; font-weight: 700; }
.group-count { padding: 3px 10px; background: linear-gradient(135deg,#FF1493,#FF69B4); color: #fff; font-size: 11px; border-radius: 12px; font-weight: 600; box-shadow: 0 2px 4px rgba(255,20,147,0.2); }
.hosts-list { padding: 8px; display: flex; flex-direction: column; gap: 6px; }
.host-item { display: flex; align-items: center; gap: 10px; padding: 10px 12px; background: rgba(255,255,255,0.5); border: 1.5px solid rgba(135,206,250,0.15); border-radius: 8px; cursor: pointer; transition: all 0.2s; }
.host-item:hover { background: rgba(135,206,250,0.08); border-color: #1E90FF; transform: translateX(4px); }
.host-item.active { background: linear-gradient(135deg,rgba(255,182,193,0.15),rgba(135,206,250,0.1)); border-color: #FF1493; box-shadow: 0 0 0 2px rgba(255,20,147,0.15); }
.host-item.offline { opacity: 0.6; }
.host-status { font-size: 10px; }
.host-status.status-online { color: #52C41A; text-shadow: 0 0 8px rgba(82,196,26,0.5); }
.host-status.status-offline { color: #FF4D4F; text-shadow: 0 0 8px rgba(255,77,79,0.5); }
.host-name { flex: 1; color: #333; font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.host-ip { color: #666; font-size: 11px; font-family: 'Consolas','Monaco',monospace; }
.connected-badge { padding: 3px 8px; background: linear-gradient(135deg,#52C41A,#73D13D); color: #fff; font-size: 10px; border-radius: 12px; font-weight: 600; box-shadow: 0 2px 4px rgba(82,196,26,0.3); }

/* 右侧终端区域 */
.terminals-area { flex: 1; display: flex; flex-direction: column; background: #f5f5f7; overflow: hidden; }
.terminals-tabs { display: flex; align-items: center; justify-content: space-between; background: rgba(255,255,255,0.95); border-bottom: 2px solid rgba(255,182,193,0.15); padding: 8px 16px; gap: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
.tabs-list { flex: 1; display: flex; gap: 8px; overflow-x: auto; }
.tab-item { display: flex; align-items: center; gap: 8px; padding: 8px 14px; background: rgba(255,255,255,0.6); border: 1.5px solid rgba(255,182,193,0.15); border-radius: 8px; cursor: pointer; transition: all 0.3s; white-space: nowrap; min-width: 200px; }
.tab-item:hover { background: rgba(255,182,193,0.08); border-color: rgba(255,20,147,0.3); }
.tab-item.active { background: linear-gradient(135deg,#FF1493,#FF69B4); border-color: #FF1493; box-shadow: 0 2px 8px rgba(255,20,147,0.3); }
.tab-icon { font-size: 14px; }
.tab-name { flex: 1; color: #333; font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; }
.tab-item.active .tab-name { color: #fff; }
.tab-ip { color: #666; font-size: 11px; font-family: 'Consolas','Monaco',monospace; }
.tab-item.active .tab-ip { color: rgba(255,255,255,0.9); }
.tab-close { padding: 2px 6px; background: transparent; border: none; color: #999; font-size: 14px; cursor: pointer; transition: all 0.2s; border-radius: 4px; }
.tab-close:hover { background: rgba(255,70,85,0.15); color: #FF4655; }
.tab-item.active .tab-close { color: rgba(255,255,255,0.8); }
.tab-item.active .tab-close:hover { background: rgba(255,255,255,0.2); color: #fff; }
.btn-close-all { display: flex; align-items: center; gap: 6px; padding: 6px 12px; background: linear-gradient(135deg,#FF4D4F,#FF7875); border: 1.5px solid #FF4D4F; border-radius: 8px; color: #fff; font-size: 12px; font-weight: 600; cursor: pointer; transition: all 0.3s; box-shadow: 0 2px 4px rgba(255,77,79,0.3); }
.btn-close-all:hover { background: linear-gradient(135deg,#DC143C,#FF4D4F); transform: translateY(-2px); box-shadow: 0 4px 12px rgba(255,77,79,0.4); }
.terminals-content { flex: 1; overflow: hidden; position: relative; background: linear-gradient(135deg, #1a1f2e 0%, #0f1419 100%); }
.terminal-panel { height: 100%; padding: 16px; }
.empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; padding: 40px; text-align: center; }
.empty-icon { font-size: 80px; margin-bottom: 20px; opacity: 0.5; animation: float 3s ease-in-out infinite; }
@keyframes float { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-20px); } }
.empty-state h3 { color: #FF69B4; font-size: 24px; margin: 0 0 12px 0; font-weight: 700; text-shadow: 0 2px 4px rgba(255,105,180,0.3); }
.empty-state p { color: #87CEEB; font-size: 15px; margin: 0 0 30px 0; font-weight: 600; }
.empty-tips { display: flex; flex-direction: column; gap: 16px; max-width: 500px; }
.tip-item { display: flex; align-items: center; gap: 12px; padding: 12px 20px; background: linear-gradient(135deg,rgba(255,182,193,0.15),rgba(135,206,250,0.1)); border: 1.5px solid rgba(255,182,193,0.3); border-radius: 8px; text-align: left; box-shadow: 0 2px 8px rgba(255,182,193,0.2); backdrop-filter: blur(10px); }
.tip-icon { font-size: 20px; flex-shrink: 0; }
.tip-item span:last-child { color: #fff; font-size: 13px; font-weight: 600; }
</style>